package com.ethanzzh.ethanzzh_xdclass.controller;

import com.ethanzzh.ethanzzh_xdclass.config.WeChatConfig;
import com.ethanzzh.ethanzzh_xdclass.model.pojo.User;
import com.ethanzzh.ethanzzh_xdclass.model.pojo.VideoOrder;
import com.ethanzzh.ethanzzh_xdclass.service.UserService;
import com.ethanzzh.ethanzzh_xdclass.service.VideoOrderService;
import com.ethanzzh.ethanzzh_xdclass.utils.JWTUtils;
import com.ethanzzh.ethanzzh_xdclass.utils.SimpleResponse;
import com.ethanzzh.ethanzzh_xdclass.utils.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;

@Controller
@RequestMapping("/api/v1/wechat")
public class WeChatController {

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private UserService userService;

    @Autowired
    private VideoOrderService videoOrderService;

    /**
     * 拼装扫一扫登录url
     *
     * @param accessPage 当前处在的网址 在哪个网址点击登录 最终还要跳转到当前的这个网址
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/login_url")
    @ResponseBody
    public SimpleResponse loginUrl(@RequestParam(value = "access_page", required = true) String accessPage) throws UnsupportedEncodingException {
        String redirectUrl = weChatConfig.getOpenRedirectUrl();//获取开放平台的重定向url

        String callbackUrl = URLEncoder.encode(redirectUrl, "GBK");//对回调地址进行编码

        //String.format 讲url里面对%s 进行赋值
        String qrcodeUrl = String.format(weChatConfig.getOpenQrcodeUrl(), weChatConfig.getOpenAppId(), callbackUrl, accessPage);

        return SimpleResponse.success(qrcodeUrl);
    }

    @GetMapping("/user/callback")
    public void wechatUserCallback(@RequestParam(value = "code") String code, String state, HttpServletResponse response) throws IOException {

        User user = userService.saveWeChatUser(code);
        if (user != null) {
            String token = JWTUtils.geneJsonWebToken(user);
            //state 当前用户的页面地址，需要拼接 http:// 这样才不会站内跳转
            response.sendRedirect(state + "?token=" + token + "&head_img" + user.getHeadImg() + "&name=" + URLEncoder.encode(user.getName(), "UTF-8"));
        }
    }

    /**
     * 微信支付回调 要用RequestMapping方式
     */
    @RequestMapping("/order/callback")
    public void orderCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {

        InputStream inputStream = request.getInputStream();
        //包装设计模式 性能高
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();
        inputStream.close();
        Map<String, String> callbackMap = WXPayUtil.xmlToMap(sb.toString());
        System.out.println(callbackMap.toString());

        SortedMap<String, String> sortedMap = WXPayUtil.getSortedMap(callbackMap);

        //判断签名是否正确
        if (WXPayUtil.isCorrectSign(sortedMap, weChatConfig.getKey())) {
            if (sortedMap.get("result_code").equals("SUCCESS")) {

                String outTradeNo = sortedMap.get("out_trade_no");
                VideoOrder dbVideoOrder = videoOrderService.findOutTradeNo(outTradeNo);
                if (dbVideoOrder.getState() == 0 && dbVideoOrder != null) { //判断逻辑看业务场景
                    VideoOrder videoOrder = new VideoOrder();
                    videoOrder.setOpenid(sortedMap.get("openid"));
                    videoOrder.setOutTradeNo(outTradeNo);
                    videoOrder.setNotifyTime(new Date());
                    //更新订单状态
                    videoOrder.setState(1);
                    int rows = videoOrderService.updateVideoOrderByOutTradeNo(videoOrder);
                    //影响行数row == 1 或者 row == 0 响应温馨成功或者失败
                    if (rows == 1) { //通知微信订单处理成功
                        response.setContentType("text/xml");
                        response.getWriter().println("success");
                        return;
                    }
                }

            }
        }
        //处理失败
        response.setContentType("text/xml");
        response.getWriter().println("success");

    }

}
